package com.app.couponsharelife.ui.main.sort
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.HomeClassBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.ui.main.home.search.SearchSelecteActivity
import com.app.couponsharelife.ui.viewfactory.NewSortFragFactory
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_newsort.*
import kotlinx.android.synthetic.main.newsort_class_rvitem.view.*
import java.util.HashMap

/**
 *Created by xct on 2019/4/23
 *Description:分类页面
 */
class NewSortFragment:LazyFragment() {
    private var myClassAdapter:MyClassAdapter?=null
    private var sortFragmentFactory: NewSortFragFactory?=null
    private var classList= arrayListOf<HomeClassBean>()
    private var layoutManager:LinearLayoutManager?=null
    private var selectedIndex=0
    private var statusBarHeight = 0
    companion object {
        fun newInstance(): NewSortFragment {
            val fragment = NewSortFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_newsort

    override fun initViews() {
        tvtitleZW.post {
            val layoutparams=tvtitleZW.layoutParams as ConstraintLayout.LayoutParams
            layoutparams.width= AppUtils.getDisplayMetrics(context!!).widthPixels
            layoutparams.height= AppUtils.getStatusBarHeight(activity!!)
            tvtitleZW.layoutParams=layoutparams
        }
        newsort_llSearch.setOnClickListener {
            val intent= Intent(activity, SearchSelecteActivity::class.java)
            intent.putExtra("Type",0)
            startActivity(intent)
        }
        //initStatusBar()
        sortFragmentFactory=NewSortFragFactory()
        layoutManager=LinearLayoutManager(context)
        newsort_rvClass.layoutManager=layoutManager
        newsort_rvClass.setItemViewCacheSize(20)
        myClassAdapter=MyClassAdapter()
        newsort_rvClass.adapter=myClassAdapter
    }
    /*private fun initStatusBar() {
        //获取status_bar_height资源的ID
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight = resources.getDimensionPixelSize(resourceId)
        }
        title_xian.layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, statusBarHeight)
    }*/
    private fun setViewPager(){
        newsort_vpTwoClass.adapter=object : FragmentPagerAdapter(childFragmentManager){
            override fun getItem(position: Int): Fragment {
                return sortFragmentFactory!!.createFragment(position,classList[position])
            }

            override fun getCount(): Int {
                return classList.size
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return classList[position].name
            }
        }
        newsort_vpTwoClass.setOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                classList[selectedIndex].isCheck=false
                classList[position].isCheck=true
                selectedIndex=position
                myClassAdapter!!.notifyDataSetChanged()
                //moveToCenter(position)
                moveToPosition(position)
            }
        })
    }
    override fun lazyLoad() {
        getData()
    }

    //将当前选中的item居中
    private fun moveToCenter(position: Int) {
        //将点击的position转换为当前屏幕上可见的item的位置以便于计算距离顶部的高度，从而进行移动居中
        val childAt = newsort_rvClass.getChildAt(position - layoutManager!!.findFirstVisibleItemPosition())
        if (childAt != null) {
            val y = childAt!!.top - newsort_rvClass.height / 2
            newsort_rvClass.smoothScrollBy(0, y)
        }

    }

    private fun moveToPosition(n: Int) {
        //mIndex = n
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        val firstItem = layoutManager!!.findFirstVisibleItemPosition()
        val lastItem = layoutManager!!.findLastVisibleItemPosition()
        //然后区分情况
        if (n <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            newsort_rvClass.smoothScrollToPosition(n)
        } else if (n <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            val top = newsort_rvClass.getChildAt(n - firstItem).top
            newsort_rvClass.scrollBy(0, top)
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            newsort_rvClass.scrollToPosition(n)
            //这里这个变量是用在RecyclerView滚动监听里面的
            //move = true
        }

    }
    private fun getData(){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        RetrofitWorker.retrofitWorker.getNewHomeClass(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<List<HomeClassBean>>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<List<HomeClassBean>>) {
                        dismissProgressDialog()
                        if (it.code==200){
                            if (it.data!!.isNotEmpty()){
                                classList.clear()
                                classList.addAll(it.data!!)
                                if (classList.isNotEmpty()){
                                    classList.removeAt(0)
                                    for (i in 0 until classList.size){
                                        classList[i].isCheck = i==0
                                    }
                                    myClassAdapter!!.notifyDataSetChanged()
                                    setViewPager()
                                }
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private inner class MyClassAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view=LayoutInflater.from(parent.context).inflate(R.layout.newsort_class_rvitem,parent,false)
            return MyClassHolder(view)
        }

        override fun getItemCount(): Int {
            return classList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (classList.isNotEmpty()){
                if (holder is MyClassHolder){
                    val bean=classList[position]
                    holder.tvName!!.text=bean.name?:""
                    if (bean.isCheck){
                        holder.itemView.setBackgroundResource(R.drawable.shape_white)
                        holder.xian!!.visibility=View.VISIBLE
                    }else{
                        holder.itemView.setBackgroundResource(R.color.gray_ef)
                        holder.xian!!.visibility=View.INVISIBLE
                    }
                    holder.itemView.setOnClickListener {
                        newsort_vpTwoClass.setCurrentItem(position,true)
                    }
                }
            }
        }
    }
    private inner class MyClassHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var tvName:TextView?=null
        var xian:View?=null
        init {
            tvName=itemview.newsort_classitem_tvName
            xian=itemview.newsort_classitem_xian
        }
    }
}